package com.atguigu.spzx.manager.service.Impl;

import cn.hutool.core.date.DateTime;
import com.atguigu.spyx.model.common.ResultCodeEnum;
import com.atguigu.spyx.model.exception.SpzxException;
import com.atguigu.spzx.manager.config.SpzxMinioConfig;
import com.atguigu.spzx.manager.service.FileService;
import com.atguigu.spzx.manager.util.MinioUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file, String module) {
        try {
            MinioClient minioClient = MinioUtil.build();
            //获取上传的文件流
            InputStream is = file.getInputStream();
            //获取上传文件的扩展名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            String filename = module
                +new DateTime().toString("/yyyy/MM-dd/")
                +System.currentTimeMillis()+"_"  + UUID.randomUUID().toString().substring(0,6)
                +suffix;
            minioClient.putObject(PutObjectArgs.builder()
                                  .bucket(SpzxMinioConfig.BUCKET)//桶名
                                  .object(filename)// 上传文件保存在桶内的路径 和文件名称
                                  //参数1：上传文件的流  参数2：上传文件的字节大小  参数3：分片  -1不分
                                  .stream(is , is.available() , -1)//要上传的文件的流
                                  .build());
            String imageUrl = SpzxMinioConfig.URL+"/"+ SpzxMinioConfig.BUCKET +"/"+filename;
            return imageUrl;
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }
    @Override
    public void delete(String path) {

        try {
            MinioClient minioClient = MinioUtil.build();
            minioClient.removeObject(RemoveObjectArgs.builder()
                                     .bucket(SpzxMinioConfig.BUCKET)
                                     .object(path.substring((SpzxMinioConfig.URL+"/"+SpzxMinioConfig.BUCKET+"/").length())) //要删除文件在桶内的路径+名称  imgs/2023/11-04/1699081709494_2b3864.png
                                     .build());
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_DELETE_ERROR,e);
        }
    }
}